import { http } from 'msw';
import { JsonResult, dyadicArr } from '../helper';
import _ from 'lodash';

const baseURL = import.meta.env.VITE_APP_BASE_API;
export default [
  // 获取当前登录用户信息
  http.get(baseURL + '/user', () => {
    // 解构查询参数
    return JsonResult.sucess({
      id: '20240101',
      name: '丁少华',
      role: 'root',
      avatar: 'https://q1.qlogo.cn/g?b=qq&nk=190848757&s=640',
    });
  }),
  http.post(baseURL + '/users', async ({ request }) => {
    // 解构请求体参数
    const params: any = await request.json();
    let { default: res } = await import('../data-base/user-list');

    // 查询条件
    if (
      !(Object.keys(params).length === 1 && params.pager) ||
      Object.keys(params).length > 2
    ) {
      const newParams = _.cloneDeep(params);
      delete newParams.pager;
      res = _.filter(res, newParams);
    }
    const len = res.length;

    // 分页
    let currentPage = params.pager.currentPage;
    if (params.pager && len > params.pager.pageSize) {
      const arr = dyadicArr(res, params.pager.pageSize);
      res = arr[params.pager.currentPage];
    } else {
      currentPage = 1; //如果查询出来的数据 少于一页，则将前端页面设置为1
    }

    return JsonResult.sucess({
      pager: { total: len, currentPage },
      list: res,
    });
  }),
];
